import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/app/yhpc/YhpcViewModel.dart';
import 'package:flutter_ahj_app/app/yhpc/yhzl/CustomSelectSbView.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/StringUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:flutter_ahj_app/base/widget/LoadingWidget.dart';
import 'package:flutter_ahj_app/base/widget/NoneData.dart';

class YhzlView extends BaseStatefulWidget {
  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    // throw UnimplementedError();
    return YhzlViewState();
  }
}

class YhzlViewState extends BaseState<YhpcViewModel, YhzlView> {
  TextEditingController _controller = TextEditingController(text: '');
  ScrollController _scrollController;

  bool canLoadMore = true;
  List _datalist; //请求的数据列表
  int pageIndex = HttpBaseConst.pageIndex;
  BuildContext _mcontext;
  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        if (canLoadMore) _getData(1);
      }
    });
    Future.delayed(Duration.zero, () {
      _getData(0);
    });
  }

  @override
  Widget initWidget() {

    return Scaffold(
      backgroundColor: Color(0xfff4f5f6),
      appBar: MTopBar(
        elevation: 0,
        title: '隐患治理',
      ).create(),
      body: _bodyView(),
    );
  }

  _bodyView() {
    return Column(
      children: [
        _searchLayout(),
        Expanded(
          child: _datalist == null ? LoadingWidget() : _datalist.length == 0 ? NoneData() :
          Container(
            margin: EdgeInsets.fromLTRB(
                Dimens.dimens16, 0, Dimens.dimens16, Dimens.dimens16),
            child: RefreshIndicator(onRefresh: () => _getData(0),
              child:
              ListView.builder(
                  shrinkWrap: true,
                  physics: AlwaysScrollableScrollPhysics(),
                  itemCount: _datalist.length,
                  controller: _scrollController,
                  itemBuilder: (context, index) {
                    _mcontext = context;
                    return _item(index);
                  }),),
          ),
        ),
      ],
    );
  }

  _item(int index) {
    return  Container(
      child: Column(
        children: [
          Container(
              padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
              decoration: BoxDecoration(
                color: SQColor.white,
                borderRadius: BorderRadius.circular(6),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Stack(
                        alignment: Alignment.center,
                        children: [
                          Image.asset(
                              "img/pxrw_zt_d.png",
                              width: 55,
                              height: Dimens.dimens20,
                              fit: BoxFit.fill),
                          JText(
                            StringUtils.getStr(_datalist[index]['hazardStatusName']),
                            color: SQColor.white,
                            fontSize: Dimens.dimens12,
                          ),
                        ],
                      ),
                    ],
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: JText(
                      StringUtils.getStr(_datalist[index]['hazardName']),
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: JText('场所/位置:  ${StringUtils.getStr(_datalist[index]['riskPointDistrictName'])}', color: SQColor.black_999999, fontSize: 14,),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: JText('登记人:  ${StringUtils.getStr(_datalist[index]['createUserName'])}', color: SQColor.black_999999, fontSize: 14,),
                  ),
                  Container(
                    margin:
                    EdgeInsets.only(top: 10, bottom: 10),
                    child: JText('${StringUtils.getStr(_datalist[index]['showTimeFieldName'])}:  ${StringUtils.getStr(_datalist[index]['showTime'])}', color: SQColor.black_999999, fontSize: 14,),
                  ),
                  SizedBox(
                    height: Dimens.dimens12,
                  ),
                  _bottomView(index),
                  SizedBox(
                    height: Dimens.dimens16,
                  ),
                ],
              )),
          Container(
            height: 10,
            color: Color(0xfff6f6f6),
            width: double.infinity,
          ),
        ],
      ),
    );
  }
  _bottomView(int index) {
    String _typeName = StringUtils.getStr(_datalist[index]["hazardStatus"]);
    return _typeName == "waitStart" ? _dtj(index) : _typeName == "waitDetermine" ?
    _dpd(index) : _typeName == "waitInvestigation" ? _dhc(index) : _typeName == "waitRectify" ? _dzg(index) : _dys(index);
  }

  _dhc(int index) {
    return Container(
      padding: EdgeInsets.only(left: 5),
      child: Row(
        children: [
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('查看详情', index);
              },
              child: Container(
                margin: EdgeInsets.only(right: 5),
                alignment: Alignment.center,
                height: 35,
                decoration: BoxDecoration(
                    color: SQColor.white,
                    border: Border.all(
                      width: 1,
                      color: Color(0xff165DFF),
                    ),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('查看详情', color: Color(0xff165DFF)),
              ),
            ),
          ),
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('上报', index);
              },
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: 5),
                width: 88,
                height: 35,
                decoration: BoxDecoration(
                    color: SQColor.white,
                    border: Border.all(
                      color: Color(0xff165DFF),
                    ),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('上报', color: Color(0xff165DFF)),
              ),
            ),
          ),
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('核查', index);
              },
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: 5),
                width: 88,
                height: 35,
                decoration: BoxDecoration(
                    color: Color(0xff165DFF),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('核查', color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }

  _dzg(int index) {
    return Container(
      padding: EdgeInsets.only(left: 5),
      child: Row(
        children: [
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('查看详情', index);
              },
              child: Container(
                margin: EdgeInsets.only(right: 5),
                alignment: Alignment.center,
                height: 35,
                decoration: BoxDecoration(
                    color: SQColor.white,
                    border: Border.all(
                      width: 1,
                      color: Color(0xff165DFF),
                    ),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('查看详情', color: Color(0xff165DFF)),
              ),
            ),
          ),
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('退回', index);
              },
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: 5),
                width: 88,
                height: 35,
                decoration: BoxDecoration(
                    color: SQColor.white,
                    border: Border.all(
                      color: Color(0xff165DFF),
                    ),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('退回', color: Color(0xff165DFF)),
              ),
            ),
          ),
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('整改', index);
              },
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: 5),
                width: 88,
                height: 35,
                decoration: BoxDecoration(
                    color: Color(0xff165DFF),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('整改', color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }

  _dys(int index) {
    return Container(
      padding: EdgeInsets.only(left: 5),
      child: Row(
        children: [
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('查看详情', index);
              },
              child: Container(
                margin: EdgeInsets.only(right: 5),
                alignment: Alignment.center,
                height: 35,
                decoration: BoxDecoration(
                    color: SQColor.white,
                    border: Border.all(
                      width: 1,
                      color: Color(0xff165DFF),
                    ),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('查看详情', color: Color(0xff165DFF)),
              ),
            ),
          ),
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('验收', index);
              },
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: 5),
                width: 88,
                height: 35,
                decoration: BoxDecoration(
                    color: Color(0xff165DFF),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('验收', color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }

  _dtj(int index) {
    return Container(
      padding: EdgeInsets.only(left: 5),
      child: Row(
        children: [
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('查看详情', index);
              },
              child: Container(
                margin: EdgeInsets.only(right: 5),
                alignment: Alignment.center,
                height: 35,
                decoration: BoxDecoration(
                    color: SQColor.white,
                    border: Border.all(
                      width: 1,
                      color: Color(0xff165DFF),
                    ),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('查看详情', color: Color(0xff165DFF)),
              ),
            ),
          ),
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('编辑', index);
              },
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: 5),
                width: 88,
                height: 35,
                decoration: BoxDecoration(
                    color: Color(0xff165DFF),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('编辑', color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }

  _dpd(int index) {
    return Container(
      padding: EdgeInsets.only(left: 5),
      child: Row(
        children: [
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('查看详情', index);
              },
              child: Container(
                margin: EdgeInsets.only(right: 5),
                alignment: Alignment.center,
                height: 35,
                decoration: BoxDecoration(
                    color: SQColor.white,
                    border: Border.all(
                      width: 1,
                      color: Color(0xff165DFF),
                    ),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('查看详情', color: Color(0xff165DFF)),
              ),
            ),
          ),
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('判定', index);
              },
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: 5),
                width: 88,
                height: 35,
                decoration: BoxDecoration(
                    color: Color(0xff165DFF),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('判定', color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }

  int _currindex;
  _yhitemClick(String title, int index) {
    switch (title) {
      case '查看详情':
        Map _m = {
          'id' : StringUtils.getStr(_datalist[index]['id'].toString()),
          'zlType' : 'xq'
        };
        Navigator.pushNamed(context, '/YhzlyhDetailView', arguments: _m);
        break;
      case '编辑':
        Navigator.pushNamed(context, '/YhdjPageView', arguments: StringUtils.getStr(_datalist[index]['id'].toString()));
        break;
      case '上报':
        _currindex = index;
        _yhzlsb();
        break;
      case '退回':
        _currindex = index;
        _yhzlth();
        break;
      case '判定':
        Map _m = {
          'id' : StringUtils.getStr(_datalist[index]['id'].toString()),
          'zlType' : 'pd'
        };
        Navigator.pushNamed(context, '/YhzlyhDetailView', arguments: _m).then((value) {
          _datalist.clear();
          _getData(0);
        });
        break;
      case '验收':
        Map _m = {
          'id' : StringUtils.getStr(_datalist[index]['id'].toString()),
          'zlType' : 'ys'
        };
        Navigator.pushNamed(context, '/YhzlyhDetailView', arguments: _m).then((value) {
          _datalist.clear();
          _getData(0);
        });
        break;
      case '整改':
        Map _m = {
          'id' : StringUtils.getStr(_datalist[index]['id'].toString()),
          'zlType' : 'zg'
        };
        Navigator.pushNamed(context, '/YhzlyhDetailView', arguments: _m).then((value) {
          _datalist.clear();
          _getData(0);
        });
        break;
      case '核查':
        Map _m = {
          'id' : StringUtils.getStr(_datalist[index]['id'].toString()),
          'zlType' : 'hc'
        };
        Navigator.pushNamed(context, '/YhzlyhDetailView', arguments: _m).then((value) {
          _datalist.clear();
          _getData(0);
        });
        break;
      default:
    }
  }

  _searchLayout() {
    return Container(
      margin: EdgeInsets.all(Dimens.dimens16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(6.0),
      ),
      child: Row(
        children: [
          Container(
            width: 20,
            height: 20,
            margin: EdgeInsets.only(left: 10),
            child: Icon(
              Icons.search,
              color: Color(0xffaaaaaa),
            ),
          ),
          Expanded(
            child: Container(
              height: Dimens.dimens36,
              child: TextField(
                controller: _controller,
                maxLines: 1,
                onSubmitted: (value) {
                  _getData(0);
                },
                decoration: InputDecoration(
                  hintText: "输入隐患名称搜索",
                  hintStyle: TextStyle(fontSize: Dimens.textSize28),
                  fillColor: Colors.white,
                  //filled = true 时为背景颜色
                  filled: true,
                  contentPadding: EdgeInsets.fromLTRB(
                      Dimens.dimens16, 0, Dimens.dimens16, 0),
                  enabledBorder: OutlineInputBorder(
                    borderRadius:
                        BorderRadius.all(Radius.circular(Dimens.dimens4)), //圆角
                    borderSide: BorderSide(color: Colors.white, width: 1), //边框
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius:
                        BorderRadius.all(Radius.circular(Dimens.dimens4)), //圆角
                    borderSide: BorderSide(color: Colors.white, width: 1), //边框
                  ),
                  suffixIcon: _controller.text.length > 0
                      ? new IconButton(
                          icon: Icon(
                            Icons.close,
                            color: SQColor.per38Black,
                            size: Dimens.dimens20,
                          ),
                          onPressed: () {
                            setState(() {
                              _controller.clear();
                              _getData(0);
                            });
                          })
                      : null,
                ),
              ),
            ),
          ),
          Container(
            width: 1,
            color: SQColor.black_BDBDBD,
            height: Dimens.dimens16,
            margin: EdgeInsets.only(right: Dimens.dimens16),
          ),
          GestureDetector(
            onTap: () {
              FocusScope.of(context).requestFocus(FocusNode());
              _getData(0);
            },
            child: Container(
              padding: EdgeInsets.only(right: Dimens.dimens16),
              height: Dimens.dimens48,
              alignment: Alignment.centerRight,
              child: Text("搜索",
                  style: TextStyle(
                      color: Color(0xff165DFF), fontSize: Dimens.textSize28)),
            ),
          ),
        ],
      ),
    );
  }


  TextEditingController _thCtr = new TextEditingController(text: '');
  _yhzlth() {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: new Row(
              children: <Widget>[
                Expanded(
                  child: Text('退回原因 '),
                  flex: 1,
                ),
                new GestureDetector(
                  child: new Icon(Icons.close),
                  onTap: () {
                    _thCtr.text = "";
                    Navigator.pop(context);
                  },
                )
              ],
            ),
            content: Card(
              elevation: 0.0,
              child: Column(
                children: <Widget>[
                  TextField(
                    controller: _thCtr,
                    maxLines: 3,
                    minLines: 3,
                    maxLength: 200,
                    decoration: InputDecoration(
                      hintText: '请输入退回原因(最多200个字)',
                      fillColor: SQColor.lightGray1,
                      border: InputBorder.none,
                      filled: true,
                    ),
                  )
                ],
              ),
            ),
            actions: <Widget>[
              CupertinoDialogAction(
                onPressed: () {
                  if (StringUtils.getStr(_thCtr.text) == "") {
                    ToastUtils.showToast("请先输入退回原因");
                    return;
                  }
                  _submitth();
                  Navigator.pop(context);
                },
                child: Text('确定'),
              ),
            ],
          );
        });
  }

  _submitth() {
    var map = {
      'hazardId': StringUtils.getStr(_datalist[_currindex]['id'].toString()),
      'rectifyRejectReason': _thCtr.text,
    };
    viewModel.yhth(map);
    viewModel.yhthDataStream().listen((event) {
      if (event['code'] == '0') {
        _thCtr.text = "";
        _datalist.clear();
        _getData(0);
        ToastUtils.showToast('退回成功');
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      print(e);
    });
  }




  TextEditingController _shangbaocontent = new TextEditingController(text: '');
  String _wgName = "",
      _wgNameid = "";
  _yhzlsb() {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: new Row(
              children: <Widget>[
                Expanded(
                  child: Text('上报原因 '),
                  flex: 1,
                ),
                new GestureDetector(
                  child: new Icon(Icons.close),
                  onTap: () {
                    _shangbaocontent.text = "";_wgNameid="";_wgName="";
                    Navigator.pop(context);
                  },
                )
              ],
            ),
            content: Card(
              elevation: 0.0,
              child: Column(
                children: <Widget>[
                  TextField(
                    controller: _shangbaocontent,
                    maxLines: 3,
                    minLines: 3,
                    maxLength: 200,
                    decoration: InputDecoration(
                      hintText: '请输入上报原因(最多200个字)',
                      fillColor: SQColor.lightGray1,
                      border: InputBorder.none,
                      filled: true,
                    ),
                  ),
                  new CustomSelectSbView(
                      callBack: (id, name) {
                       _wgName = name;
                       _wgNameid = id;
                       print('-----------');
                       if(!StringUtils.isEmpty(_wgNameid)) {
                         _yhzlsb();
                       }
                      },mcontext: _mcontext, wgName: _wgName,wgNameid: _wgNameid,
                  )
                ],
              ),
            ),
            actions: <Widget>[
              CupertinoDialogAction(
                onPressed: () {
                  if (StringUtils.getStr(_wgNameid) == "") {
                    ToastUtils.showToast("请先选择确认人");
                    return;
                  }
                  if (StringUtils.getStr(_shangbaocontent.text) == "") {
                    ToastUtils.showToast("请先输入上报原因");
                    return;
                  }
                  _submit();
                  Navigator.pop(context);
                },
                child: Text('确定'),
              ),
            ],
          );
        });
  }

  _submit() {
    var map = {
      'hazardId': StringUtils.getStr(_datalist[_currindex]['id'].toString()),
      'reportReason': _shangbaocontent.text,
      'reportConfirmOpenId': StringUtils.getStr(_wgNameid),
    };
    viewModel.yhsb(map);
    viewModel.yhsbDataStream().listen((event) {
      if (event['code'] == '0') {
        _shangbaocontent.text = "";_wgNameid="";_wgName="";
        ToastUtils.showToast('上报成功');
        _datalist.clear();
        _getData(0);
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      print(e);
    });
  }


  ///获得数据
  _getData(int type) async {
    if (type == 0) {
      //刷新
      pageIndex = HttpBaseConst.pageIndex;
    } else {
      //加载更多
      pageIndex += 1;
    }

    print(_controller.text);
    var map = {
      'size': HttpBaseConst.pageSize,
      'current': pageIndex,
      'hazardName': _controller.text,
    };

    viewModel.getYhzlListData(map);
    viewModel.getYhzlListDataStream().listen((result) {
      print(result);
      if (result['code'] == "0") {
        if (_datalist == null) _datalist = List();
        if (result == null ||
            result['data'] == null ||
            result['data']['total'] == 0 ||
            result['data']['records'] == null ||
            result['data']['records'].length == 0) {
          setState(() {
            if (type == 0) {
              //刷新
              _datalist.clear();
            } else {
              //加载更多
            }
          });
        } else {
          setState(() {
            if (type == 0) {
              //刷新
              _datalist.clear();
            } else {
              //加载更多
            }
            _datalist.addAll(result['data']['records']);
          });
        }
        setState(() {
          canLoadMore =
          _datalist.length == result['data']['total'] ? false : true;
        });
        print("******************length = ${_datalist.length}");
      } else {
        setState(() {
          _datalist = List();
        });
        ToastUtils.showToast(result['msg']);
      }
    });
  }
}
